package org.dromara.system.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.ZfbConfig;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AlipayUtil {

    private final static String SERVER_URL = "https://openapi.alipay.com/gateway.do";
    private final static String SIGN_TYPE = "RSA2";
    private final static String FORMAT = "json";
    private final static String CHARSET = "UTF-8";


    public AlipayClient getAlipayClient(ZfbConfig zfbConfig) throws AlipayApiException {
        AlipayClient alipayClient = null;
        /** 初始化 **/
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        /** 支付宝网关 **/
        certAlipayRequest.setServerUrl(SERVER_URL);
        /** 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        certAlipayRequest.setAppId(zfbConfig.getAppId());
        /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport  **/
        certAlipayRequest.setPrivateKey(zfbConfig.getPrivateKey());
        /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
        certAlipayRequest.setCertPath(zfbConfig.getCertPath());
        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setAlipayPublicCertPath(zfbConfig.getAlipayPublicCertPath());
        /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setRootCertPath(zfbConfig.getRootCertPath());
        /** 设置签名类型 **/
        certAlipayRequest.setSignType(SIGN_TYPE);
        /** 设置请求格式，固定值json **/
        certAlipayRequest.setFormat(FORMAT);
        /** 设置编码格式 **/
        certAlipayRequest.setCharset(CHARSET);
        alipayClient = new DefaultAlipayClient(certAlipayRequest);
        return alipayClient;
    }


}
